<template>
  <view class="container">
    <scroll-view scroll-y class="page">
      <view class="form-container">
        <view class="form-title">申请志愿活动</view>

        <view class="form-item">
          <text class="label">活动标题</text>
          <input type="text" v-model="activityForm.title" placeholder="请输入活动标题" class="input" maxlength="100" />
        </view>

        <view class="form-item">
          <text class="label">活动类型</text>
          <picker mode="selector" :range="activityTypes" range-key="name" @change="onTypeChange" class="picker">
            <view class="picker-selector">
              <text>{{ selectedType.name || "请选择活动类型" }}</text>
              <text class="arrow">▶</text>
            </view>
          </picker>
        </view>

        <!-- 报名时间 -->
        <view class="form-item">
          <text class="label">报名时间</text>
          <view class="datetime-container">
            <view class="datetime-item">
              <text class="sub-label">开始报名时间</text>
              <view class="datetime-picker">
                <picker mode="date" :value="registrationStartDate" :start="currentDate" @change="onRegistrationStartDateChange" class="date-picker">
                  <view class="picker-selector">
                    <text>{{ registrationStartDate || "请选择开始日期" }}</text>
                    <text class="arrow">▶</text>
                  </view>
                </picker>

                <picker mode="time" :value="registrationStartTime" @change="onRegistrationStartTimeChange" class="time-picker">
                  <view class="picker-selector">
                    <text>{{ registrationStartTime || "请选择开始时间" }}</text>
                    <text class="arrow">▶</text>
                  </view>
                </picker>
              </view>
            </view>

            <view class="datetime-item">
              <text class="sub-label">结束报名时间</text>
              <view class="datetime-picker">
                <picker mode="date" :value="registrationEndDate" :start="currentDate" @change="onRegistrationEndDateChange" class="date-picker">
                  <view class="picker-selector">
                    <text>{{ registrationEndDate || "请选择结束日期" }}</text>
                    <text class="arrow">▶</text>
                  </view>
                </picker>

                <picker mode="time" :value="registrationEndTime" @change="onRegistrationEndTimeChange" class="time-picker">
                  <view class="picker-selector">
                    <text>{{ registrationEndTime || "请选择结束时间" }}</text>
                    <text class="arrow">▶</text>
                  </view>
                </picker>
              </view>
            </view>
          </view>
        </view>

        <view class="form-item">
          <text class="label">活动时间</text>
          <view class="datetime-container">
            <view class="datetime-item">
              <text class="sub-label">开始时间</text>
              <view class="datetime-picker">
                <picker mode="date" :value="startDate" :start="currentDate" @change="onStartDateChange" class="date-picker">
                  <view class="picker-selector">
                    <text>{{ startDate || "请选择开始日期" }}</text>
                    <text class="arrow">▶</text>
                  </view>
                </picker>

                <picker mode="time" :value="startTime" @change="onStartTimeChange" class="time-picker">
                  <view class="picker-selector">
                    <text>{{ startTime || "请选择开始时间" }}</text>
                    <text class="arrow">▶</text>
                  </view>
                </picker>
              </view>
            </view>

            <view class="datetime-item">
              <text class="sub-label">结束时间</text>
              <view class="datetime-picker">
                <picker mode="date" :value="endDate" :start="currentDate" @change="onEndDateChange" class="date-picker">
                  <view class="picker-selector">
                    <text>{{ endDate || "请选择结束日期" }}</text>
                    <text class="arrow">▶</text>
                  </view>
                </picker>

                <picker mode="time" :value="endTime" @change="onEndTimeChange" class="time-picker">
                  <view class="picker-selector">
                    <text>{{ endTime || "请选择结束时间" }}</text>
                    <text class="arrow">▶</text>
                  </view>
                </picker>
              </view>
            </view>
          </view>
        </view>

        <view class="form-item">
          <text class="label">活动描述</text>
          <textarea v-model="activityForm.description" placeholder="请输入活动详细描述" class="textarea" maxlength="500" />
        </view>

        <view class="form-item">
          <text class="label">活动地点</text>
          <input type="text" v-model="activityForm.location" placeholder="请输入活动地点" class="input" maxlength="255" />
        </view>

        <view class="form-item">
          <text class="label">最大参与人数</text>
          <input type="number" v-model="activityForm.maxParticipants" placeholder="请输入最大参与人数" class="input" />
        </view>

        <view class="form-item">
          <text class="label">活动封面图</text>
          <view class="image-upload">
            <view class="image-preview" v-if="activityForm.activityImage" @tap="previewImage">
              <image :src="activityForm.activityImage" mode="aspectFill" class="preview-image" />
              <view class="remove-image" @tap.stop="removeImage">✕</view>
            </view>

            <view class="upload-area" v-else @tap="chooseImage">
              <text class="upload-icon">+</text>
              <text class="upload-text">上传封面图</text>
            </view>
          </view>
        </view>

        <button @tap="submitActivity" class="submit-button">提交申请</button>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { addVoluntaryAPI } from '@/services/voluntary'

// 获取当前日期
const getCurrentDate = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 获取当前时间
const getCurrentTime = () => {
  const now = new Date()
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  return `${hours}:${minutes}`
}

// 当前日期（用于限制日期选择器的最小值）
const currentDate = ref(getCurrentDate())

// 表单数据
const activityForm = reactive({
  treeId: null,
  title: '',
  description: '',
  activityType: null,
  registrationStartTime: '',
  registrationEndTime: '',
  startTime: '',
  endTime: '',
  location: '',
  maxParticipants: null,
  activityImage: ''
})

const treeInfo = ref({})

// 日期和时间分离存储
const startDate = ref('')
const startTime = ref('')
const endDate = ref('')
const endTime = ref('')

// 报名时间日期和时间分离存储
const registrationStartDate = ref('')
const registrationStartTime = ref('')
const registrationEndDate = ref('')
const registrationEndTime = ref('')

// 计算完整的开始和结束时间
const fullStartTime = computed(() => {
  if (startDate.value && startTime.value) {
    return `${startDate.value}T${startTime.value}:00`
  }
  return ''
})

const fullEndTime = computed(() => {
  if (endDate.value && endTime.value) {
    return `${endDate.value}T${endTime.value}:00`
  }
  return ''
})

// 计算完整的报名开始和结束时间
const fullRegistrationStartTime = computed(() => {
  if (registrationStartDate.value && registrationStartTime.value) {
    return `${registrationStartDate.value}T${registrationStartTime.value}:00`
  }
  return ''
})

const fullRegistrationEndTime = computed(() => {
  if (registrationEndDate.value && registrationEndTime.value) {
    return `${registrationEndDate.value}T${registrationEndTime.value}:00`
  }
  return ''
})

// 活动类型选项
const activityTypes = ref([
  { id: 1, name: '监测' },
  { id: 2, name: '维护' },
  { id: 3, name: '清洁' },
  { id: 4, name: '宣传' }
])

const selectedType = ref({})

// 接收从TreeDetail页面传递的tree_id
onLoad((options) => {
  if (options && options.treeId) {
    activityForm.tree_id = parseInt(options.treeId)
  }
})

// 活动类型选择
const onTypeChange = (e) => {
  const index = e.detail.value
  selectedType.value = activityTypes.value[index]
  activityForm.activityType = selectedType.value.id
}

// 开始日期选择
const onStartDateChange = (e) => {
  startDate.value = e.detail.value
  updateActivityFormTime()
}

// 开始时间选择
const onStartTimeChange = (e) => {
  startTime.value = e.detail.value
  updateActivityFormTime()
}

// 结束日期选择
const onEndDateChange = (e) => {
  endDate.value = e.detail.value
  updateActivityFormTime()
}

// 结束时间选择
const onEndTimeChange = (e) => {
  endTime.value = e.detail.value
  updateActivityFormTime()
}

// 报名开始日期选择
const onRegistrationStartDateChange = (e) => {
  registrationStartDate.value = e.detail.value
  updateActivityFormRegistrationTime()
}

// 报名开始时间选择
const onRegistrationStartTimeChange = (e) => {
  registrationStartTime.value = e.detail.value
  updateActivityFormRegistrationTime()
}

// 报名结束日期选择
const onRegistrationEndDateChange = (e) => {
  registrationEndDate.value = e.detail.value
  updateActivityFormRegistrationTime()
}

// 报名结束时间选择
const onRegistrationEndTimeChange = (e) => {
  registrationEndTime.value = e.detail.value
  updateActivityFormRegistrationTime()
}

// 更新活动表单中的时间
const updateActivityFormTime = () => {
  activityForm.startTime = fullStartTime.value
  activityForm.endTime = fullEndTime.value
}

// 更新活动表单中的报名时间
const updateActivityFormRegistrationTime = () => {
  activityForm.registrationStartTime = fullRegistrationStartTime.value
  activityForm.registrationEndTime = fullRegistrationEndTime.value
}

// 选择图片
const chooseImage = () => {
  uni.chooseMedia({
    count: 1,
    mediaType: ['image'],
    success: (res) => {
      const file = res.tempFiles[0]
      uni.uploadFile({
        url: '/uploadFile',
        filePath: file.tempFilePath,
        name: 'file',
        formData: {
          path: 'activityImage',
        },
        success: (uploadRes) => {
          if (uploadRes.statusCode === 200) {
            const result = JSON.parse(uploadRes.data)
            activityForm.activityImage = result.data
          }
        },
        fail: (error) => {
          console.log(error)
        }
      })
    },
    fail: (err) => {
      console.error('选择图片失败', err)
      uni.showToast({
        title: '选择图片失败',
        icon: 'none'
      })
    }
  })
}

// 预览图片
const previewImage = () => {
  uni.previewImage({
    urls: [activityForm.activityImage]
  })
}

// 移除图片
const removeImage = () => {
  activityForm.activityImage = ''
}

// 提交活动申请
const submitActivity = async () => {
  // 表单验证
  if (!activityForm.title) {
    uni.showToast({ title: '请输入活动标题', icon: 'none' })
    return
  }

  if (!activityForm.activityType) {
    uni.showToast({ title: '请选择活动类型', icon: 'none' })
    return
  }

  if (!activityForm.registrationStartTime) {
    uni.showToast({ title: '请选择报名开始时间', icon: 'none' })
    return
  }

  if (!activityForm.registrationEndTime) {
    uni.showToast({ title: '请选择报名结束时间', icon: 'none' })
    return
  }

  if (new Date(activityForm.registrationStartTime) >= new Date(activityForm.registrationEndTime)) {
    uni.showToast({ title: '报名开始时间必须早于报名结束时间', icon: 'none' })
    return
  }

  if (!activityForm.startTime) {
    uni.showToast({ title: '请选择活动开始时间', icon: 'none' })
    return
  }

  if (!activityForm.endTime) {
    uni.showToast({ title: '请选择活动结束时间', icon: 'none' })
    return
  }

  if (new Date(activityForm.startTime) >= new Date(activityForm.endTime)) {
    uni.showToast({ title: '活动开始时间必须早于活动结束时间', icon: 'none' })
    return
  }

  // 报名时间应在活动时间之前
  if (new Date(activityForm.registrationEndTime) >= new Date(activityForm.startTime)) {
    uni.showToast({ title: '报名结束时间必须早于活动开始时间', icon: 'none' })
    return
  }

  if (!activityForm.location) {
    uni.showToast({ title: '请输入活动地点', icon: 'none' })
    return
  }
  
  if (!activityForm.maxParticipants) {
    uni.showToast({ title: '请输入最大参与人数', icon: 'none' })
    return
  }

  // 校验最大参与人数是否为正整数
  const maxParticipants = parseInt(activityForm.maxParticipants);
  if (isNaN(maxParticipants) || maxParticipants <= 0 || maxParticipants != activityForm.maxParticipants) {
    uni.showToast({ title: '最大参与人数必须为正整数', icon: 'none' })
    return
  }

  // 调用API提交数据
  const result = await addVoluntaryAPI(activityForm)
  if (result.code === 1) {
    // 提交成功
    uni.showToast({
      title: '申请提交成功',
      icon: 'success'
    })
    // 返回上一页
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  } else {
    // 提交失败
    uni.showToast({
      title: '申请提交失败',
      icon: 'none'
    })
  }
}

// 获取传递的参数
onLoad((options) => {
  if (options.treeInfo) {
    treeInfo.value = JSON.parse(decodeURIComponent(options.treeInfo))
    activityForm.treeId = treeInfo.value.treeId
    activityForm.location = treeInfo.value.locationAddress
  }
})
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.page {
  padding: 20rpx;
}

.form-container {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

.form-title {
  font-size: 36rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 40rpx;
  color: #333;
}

.form-item {
  margin-bottom: 30rpx;
}

.label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 15rpx;
  font-weight: bold;
}

.input,
.textarea {
  width: 100%;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 10rpx;
  box-sizing: border-box;
  font-size: 28rpx;
  background-color: #fff;
}

.input {
  height: 80rpx;
  line-height: 80rpx;
}

.textarea {
  height: 200rpx;
}

.picker {
  width: 100%;
}

.picker-selector {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 10rpx;
  background-color: #fff;
  color: #666;
}

.arrow {
  color: #999;
  font-size: 24rpx;
}

.datetime-container {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.datetime-item {
  display: flex;
  flex-direction: column;
}

.sub-label {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.datetime-picker {
  display: flex;
  gap: 20rpx;

  .date-picker,
  .time-picker {
    flex: 1;
  }
}

// 图片上传区域样式
.image-upload {
  .image-preview {
    position: relative;
    width: 200rpx;
    height: 200rpx;

    .preview-image {
      width: 100%;
      height: 100%;
      border-radius: 10rpx;
    }

    .remove-image {
      position: absolute;
      top: -15rpx;
      right: -15rpx;
      width: 40rpx;
      height: 40rpx;
      border-radius: 50%;
      background-color: #ff4757;
      color: white;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 24rpx;
    }
  }

  .upload-area {
    width: 200rpx;
    height: 200rpx;
    border: 2rpx dashed #ddd;
    border-radius: 10rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #999;

    .upload-icon {
      font-size: 60rpx;
    }

    .upload-text {
      font-size: 24rpx;
      margin-top: 10rpx;
    }
  }
}

.submit-button {
  height: 80rpx;
  text-align: center;
  line-height: 80rpx;
  margin-top: 50rpx;
  color: #fff;
  border-radius: 80rpx;
  font-size: 30rpx;
  background: linear-gradient(45deg, #35c8a9, #2a9d8f);
  box-shadow: 0 10rpx 20rpx rgba(53, 200, 169, 0.3);
}
</style>